package command

import (
	"encoding/hex"
	"encoding/json"
	"gdfs-center/db"
	"gdfs-center/engine"
	"gdfs-center/err"
	"gdfs-center/logcat"
	"gdfs-center/socket/codec"
	"log"
	"net"
	"strconv"
	"sync"
)

//解析上报的存储服务器的信息
func AnalysisUploadInfo(conn net.Conn, data *codec.DataDockPackage) *codec.Response {
	var uploadinfo codec.UploadStoreInfo
	var store db.Store
	hexbyte, _ := hex.DecodeString(data.Data)
	log.Println("####Cmd:", data.Cmd, "hexdata =", string(hexbyte), "ip:", uploadinfo.IP)
	jsonerr := json.Unmarshal(hexbyte, &uploadinfo)
	if jsonerr != nil {
		log.Println("###json err:", jsonerr)
		return codec.GetResponse(1, data.SerialNum, err.JSONERR, err.Errortype[err.JSONERR])
	}
	//查询数据库是否存在重复的记录
	db.GetDB().Where("store_id = ?", uploadinfo.ID).First(&store)
	if store != (db.Store{}) {
		//更新
		store.HttpPort = uploadinfo.HttpPort
		store.Weight = uploadinfo.Weight
		store.StoreIp = uploadinfo.IP
		store.TcpPort = uploadinfo.TcpPort
		er := db.GetDB().Save(&store).Error
		if er != nil {
			log.Println("###更新失败")
			return codec.GetResponse(1, data.SerialNum, err.SAVEERR, err.Errortype[err.SAVEERR])
		}
	} else {
		//存入数据库
		store.HttpPort = uploadinfo.HttpPort
		store.NodeId = ""
		store.Weight = uploadinfo.Weight
		store.StoreId = uploadinfo.ID
		store.StoreIp = uploadinfo.IP
		store.TcpPort = uploadinfo.TcpPort
		tx := db.GetDB().Create(&store)
		if tx.Error != nil {
			log.Println("###存储失败")
			return codec.GetResponse(1, data.SerialNum, err.SAVEERR, err.Errortype[err.SAVEERR])
		}
	}
	httport, _ := strconv.ParseInt(uploadinfo.HttpPort, 10, 64)
	//注册到内存
	s := &engine.Storage{
		StoreID:  uploadinfo.ID,
		Ip:       uploadinfo.IP,
		NodeID:   store.NodeId,
		HttpPort: uint64(httport),
		Alive:    false,
		Weight:   int64(uploadinfo.Weight),
		Conn:     conn,
		Mux:      sync.RWMutex{},
	}
	logcat.GetLog().Sugar().Info("###注册到内存-----------------!")
	engine.RegStoreInstance(s)
	return codec.GetResponse(1, data.SerialNum, err.SUCESS, err.Errortype[err.SUCESS])
}
